package com.book.common;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;

import com.book.entity.Teacher;
import com.book.utils.BeanUtils;
import com.github.drinkjava2.jsqlbox.ActiveRecord;




/**
 * 
 * 控制类基类
 * @author jiang
 *
 */

public abstract class BaseController<T> {
	
	public abstract ActiveRecord<T>  getRecord() ;
	
	public abstract String  getPKFielName() ;
	
	public abstract String getModule();
	
	
	public String index(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		System.out.println("进入 UserController 的 index 方法。。。。");
		
		
		req.setAttribute("datalist", getRecord().findAll());

		return String.format("/%s/list",getModule() );

	}

	public String add(HttpServletRequest req, HttpServletResponse resp ) throws Exception {

		System.out.println("进入 UserController 的 add 方法。。。。");
	
		return String.format("/%s/edit",getModule() );
	
	}

	
	public  String edit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
           
		String id_str = req.getParameter("id");
		int id = Integer.parseInt(id_str);
		
		T eo = getRecord().loadById(id);
		
		req.setAttribute("eo", eo);
		
		return String.format("/%s/edit",getModule() );
		
	}
	
	
	
	public String del(HttpServletRequest req, HttpServletResponse resp) throws Exception {

		try {
			String id_str = req.getParameter("id");
			int id = Integer.parseInt(id_str);
			getRecord().deleteById(id);
		} catch (Exception e) { 
			e.printStackTrace();
			return "删除失败，请检查";
		}
		return "删除成功";
	}
	
	
	public String save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
			
		ActiveRecord<?> eo = getRecord();
		
		Enumeration<String> names = req.getParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			String value = req.getParameter(name);
			BeanUtils.setProperty(eo, name, value); 
			System.out.println(String.format("Name = %s; Value = %s", name,value));
		}
		
		System.out.println(eo.toString());
		
		Object pkvalue =  eo.getField(getPKFielName());
		
		
		try {
		  //判断当前是新增 还是修改   
		if(pkvalue != null && ((Integer)pkvalue)>0) {
				//修改
				eo.update();
		}else {
			//新增
			eo.insert();
		   }		 
		}catch (Exception e) {
			e.printStackTrace();
			if(e.getMessage().contains("Duplicate entry")) {
				//有条目重复
				String msg = e.getMessage();
				int beginIndex = msg.indexOf("for key")+7;
				int endIndex = msg.indexOf("Query:");
				String key = msg.substring(beginIndex,endIndex);
				return String.format("%s重复，请重新填写", key);
			}else {
				return "更新失败，请联系管理员检查日志";
			}
			
			
		}	
				return "更新成功！";
	}
	
}
